import {ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {OptionsInterface, SearchCommonVO, temperatureManage, UserLogin} from "../../core/services/types";
import {Subject} from "rxjs";
import {MyTableConfig} from "../../share/components/ant-table/ant-table.component";
import {NzModalService} from "ng-zorro-antd/modal";
import {MessageService} from "../../core/services/common/message.service";
import {Location} from "@angular/common";
import {UserInfoService} from "../../core/services/store/user-info.service";
import {WindowService} from "../../core/services/common/window.service";
import {NzTableQueryParams} from "ng-zorro-antd/table";
import {finalize, takeUntil} from "rxjs/operators";
import {UserInfoKey} from "../../configs/constant";
import {UserTemperatureService} from "../../core/services/http/user-temperature.service";
import {endOfDay, startOfDay} from 'date-fns';
import {MapPipe, MapSet} from "../../share/pipes/map.pipe";
import {NzMessageService} from "ng-zorro-antd/message";

interface SearchParam {
  beginTime: Date | number;
  endTime: Date | number;
  sign?: number | any;
  name?: string | any;
  departmentName?: string | any;
}

@Component({
  selector: 'app-user-temperature',
  templateUrl: './user-temperature.component.html',
  styleUrls: ['./user-temperature.component.less']
})
export class UserTemperatureComponent implements OnInit {
  userLogin!: UserLogin; // 当前选中的任务对象
  searchParam: Partial<SearchParam> = {};
  @ViewChild('operationTpl', {static: true}) operationTpl!: TemplateRef<any>;
  tableConfig!: MyTableConfig;
  dataList: temperatureManage[] = [];
  checkedCashArray: temperatureManage[] = [];
  Options!: OptionsInterface[];
  isCollapse = false;
  private destory$ = new Subject<void>();

  constructor(private dataService: UserTemperatureService, private modalSrv: NzModalService, private cdr: ChangeDetectorRef,
              private messageService: MessageService,
              private location: Location,
              private userInfoService: UserInfoService,
              private windowServe: WindowService, private message: NzMessageService) {
  }

  selectedChecked(e: any): void {
    this.checkedCashArray = [...e];
  }


  getDataList(e?: NzTableQueryParams): void {
    this.tableConfig.loading = true;
    const start = startOfDay((this.searchParam.beginTime as Date)).getTime();
    const last = endOfDay((this.searchParam.endTime as Date)).getTime();
    if (start < last) {
      const params: SearchCommonVO<SearchParam> = {
        pageSize: this.tableConfig.pageSize!,
        pageNum: e?.pageIndex || this.tableConfig.pageIndex!,
        filters: {
          beginTime: start,
          endTime: last,
          sign: this.searchParam.sign,
          name: this.searchParam.name,
          departmentName: this.searchParam.departmentName
        }
      };
      this.dataService.getUserTemperatureList(params).pipe(finalize(() => {
        this.tableLoading(false);
      })).subscribe((data => {
        const {list, total, pageNum} = data;
        this.dataList = [...list];
        this.tableConfig.total = total!;
        this.tableConfig.pageIndex = pageNum!;
        this.tableLoading(false);
        this.checkedCashArray = [...this.checkedCashArray];
      }));
    } else {
      this.message.error('开始时间不能超过结束时间');
    }
  }

  resetForm(): void {
    this.searchParam = {
      beginTime: startOfDay(new Date()),
      endTime: endOfDay(new Date()),
      sign: null,
      name: null,
      departmentName: null,
    };
    this.getDataList();
  }

  // 触发表格变更检测
  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  // 修改一页几条

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  initParam(): void {
    this.userInfoService.getLoginUserInfoMode().pipe(takeUntil(this.destory$)).subscribe(currentUserLogin => {
      this.userLogin = currentUserLogin;
      if (this.userLogin.userId === -1) {
        this.userLogin = JSON.parse(this.windowServe.getStorage(UserInfoKey)!);
        this.userInfoService.setLoginUserInfoMode(this.userLogin);
      }
    });
  }

  ngOnDestroy(): void {
    this.destory$.next();
    this.destory$.complete();
  }

  ngOnInit(): void {
    this.Options = [...MapPipe.transformMapToArray(MapSet.sign)];
    this.searchParam.beginTime = startOfDay(new Date());
    this.searchParam.endTime = endOfDay(new Date());
    //  console.log(this.searchParam.beginTime);
    this.initParam();
    this.initTable();
  }

  private initTable(): void {
    this.tableConfig = {
      showCheckbox: false,
      headers: [
        {
          title: '姓名',
          field: 'name',
          width: 50,
        },
        {
          title: '部门',
          field: 'departmentName',
          width: 50,
        },
        {
          title: '打卡记录',
          field: 'temperatureRecords',
          tdTemplate: this.operationTpl,
          width: 250,
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1,
    };
  }
}

